package com.sina.shop.manage.controller;

import com.sina.shop.util.KeyUtils;
import com.sina.shop.web.BaseController;
import com.sina.shop.manage.form.LoginForm;
import org.apache.commons.codec.binary.Base64;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.security.Key;

/**
 * created  on 13/06/2017.
 */
@Controller("adminController")
@RequestMapping("admin")
public class AdminController extends BaseController {

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public ModelAndView login(HttpServletRequest request) {

        LOG.info("com:{}", 1);

        ModelAndView mv = new ModelAndView("admin/login");

        //得到密钥对
        Key key[] = KeyUtils.createRSAKeyPair(1024, null);


        HttpSession session = request.getSession();

        session.setAttribute("keyPr", key[1]);
        mv.addObject("keyPu", Base64.encodeBase64String(key[0].getEncoded()));

        return mv;
    }


    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ModelAndView login(@Valid LoginForm form, RedirectAttributes redirectAttribute, HttpServletRequest request) {
        LOG.debug("form : {}", form);

        //解密(测试时注释)
        Key keyPr = (Key) request.getSession().getAttribute("keyPr");
        String psd = KeyUtils.decryptWithRsaAsString(form.getPassword(), keyPr);
        form.setPassword(psd);

        ModelAndView mv = new ModelAndView("redirect:/admin/login");
        UsernamePasswordToken token = new UsernamePasswordToken(form.getAccount(), form.getPassword(), form.getRememberMe());
        //token.setRememberMe(true);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(token);
            currentUser.getSession().setAttribute("username", form.getAccount());
            mv.setViewName("redirect:/home");
        } catch (AuthenticationException e) {
            LOG.info("account[{}] login failure,because of {}", form.getAccount(), e.getMessage());
            redirectAttribute.addFlashAttribute(MSG, "帐户或密码错误")
                    .addFlashAttribute("account", form.getAccount());
            //.addFlashAttribute("password", form.getPassword());

        }
        return mv;
    }
}